#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
系统级摄像头测试脚本 - 使用系统Python环境
无需虚拟环境，直接使用系统安装的OpenCV
"""

import sys
import cv2
import numpy as np
import time

def test_camera(camera_id=0):
    """测试摄像头是否可用"""
    print(f"🔍 测试摄像头 {camera_id}...")
    
    cap = cv2.VideoCapture(camera_id)
    
    if not cap.isOpened():
        print(f"❌ 摄像头 {camera_id} 无法打开")
        return False
    
    # 获取摄像头信息
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    
    print(f"✅ 摄像头 {camera_id} 可用")
    print(f"📸 分辨率: {width}x{height}")
    print(f"🎬 帧率: {fps}")
    
    # 测试读取几帧
    print("📷 测试读取帧...")
    for i in range(5):
        ret, frame = cap.read()
        if ret:
            print(f"  帧 {i+1}: ✅ {frame.shape}")
        else:
            print(f"  帧 {i+1}: ❌ 读取失败")
            break
        time.sleep(0.1)
    
    cap.release()
    return True

def show_camera_preview(camera_id=0):
    """显示摄像头预览"""
    print(f"📺 启动摄像头 {camera_id} 预览...")
    print("按 'q' 键退出预览")
    
    cap = cv2.VideoCapture(camera_id)
    
    if not cap.isOpened():
        print(f"❌ 无法打开摄像头 {camera_id}")
        return
    
    # 设置摄像头参数
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    cap.set(cv2.CAP_PROP_FPS, 30)
    
    frame_count = 0
    start_time = time.time()
    
    while True:
        ret, frame = cap.read()
        if not ret:
            print("❌ 无法读取摄像头帧")
            break
        
        frame_count += 1
        
        # 添加帧计数和时间戳
        current_time = time.time()
        fps = frame_count / (current_time - start_time) if (current_time - start_time) > 0 else 0
        
        # 绘制信息
        cv2.putText(frame, f"Frame: {frame_count}", (10, 30), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
        cv2.putText(frame, f"FPS: {fps:.1f}", (10, 60), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
        cv2.putText(frame, "Press 'q' to quit", (10, frame.shape[0] - 20), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1)
        
        # 显示帧
        cv2.imshow('Camera Test', frame)
        
        # 检查按键
        key = cv2.waitKey(1) & 0xFF
        if key == ord('q'):
            break
    
    # 最终统计
    total_time = time.time() - start_time
    avg_fps = frame_count / total_time if total_time > 0 else 0
    
    print(f"\n📊 测试统计:")
    print(f"总帧数: {frame_count}")
    print(f"运行时间: {total_time:.1f}s")
    print(f"平均FPS: {avg_fps:.2f}")
    
    cap.release()
    cv2.destroyAllWindows()

def main():
    print("🚀 系统摄像头测试程序")
    print("=" * 40)
    
    # 检查OpenCV版本
    print(f"📦 OpenCV版本: {cv2.__version__}")
    
    # 检查CUDA支持
    try:
        cuda_devices = cv2.cuda.getCudaEnabledDeviceCount()
        print(f"🚀 CUDA设备数: {cuda_devices}")
    except:
        print("💻 CUDA不可用，使用CPU")
    
    # 查找可用摄像头
    print("\n🔍 扫描可用摄像头...")
    available_cameras = []
    
    for i in range(4):  # 检查前4个摄像头
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            available_cameras.append(i)
            cap.release()
    
    if not available_cameras:
        print("❌ 未找到可用摄像头")
        print("💡 请检查:")
        print("  - 摄像头是否正确连接")
        print("  - USB摄像头是否被识别")
        print("  - 权限是否正确")
        return
    
    print(f"✅ 找到摄像头: {available_cameras}")
    
    # 测试第一个可用摄像头
    camera_id = available_cameras[0]
    
    if test_camera(camera_id):
        print(f"\n🎬 启动摄像头 {camera_id} 预览...")
        show_camera_preview(camera_id)
    
    print("🎉 测试完成")

if __name__ == "__main__":
    main()